package org.polaris.authority.interceptor;

import org.polaris.authority.annotation.PolarisPermission;
import org.polaris.basic.tool.BasicMap;
import org.polaris.org.domain.Employee;
import org.polaris.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthorityInterceptor implements HandlerInterceptor {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录拦截
        String token = request.getHeader("token");
        Employee user =(Employee) BasicMap.loginMap.get(token);
        if (Objects.isNull(user)){
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }

        //权限拦截
        //System.out.println(handler.getClass());
        //System.out.println(handler);
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取当前方法名
            Method method = handlerMethod.getMethod();
            PolarisPermission methodAnnotation = method.getAnnotation(PolarisPermission.class);
            //判断是否有权限注解
            if (Objects.isNull(methodAnnotation)){
                return true;
            }

            //获取当前用户所有权限
            Long userId = user.getId();
            List<String> sns = employeeMapper.selectSnsByUserId(userId);

            //获取当前权限
            String sn = method.getDeclaringClass().getSimpleName() + ":" + method.getName();

            if (!sns.contains(sn)){
                response.getWriter().write("{\"success\":false,\"message\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
